﻿// Load the required SharePoint libraries.
$(document).ready(function () {

    // Get the URI decoded URLs.
    AGSamples.translator.hostWebUrl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );

    // The js files are in a URL in the form:
    // web_url/_layouts/15/resource_file
    var scriptbase = AGSamples.translator.hostWebUrl + "/_layouts/15/";

    // Load the js files and continue to
    // the execOperation function.
    $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js",
                function () {
                    $.getScript(scriptbase + "SP.RequestExecutor.js",
                    function () {
                        $.getScript(scriptbase + "SP.RequestExecutor.js",
                            AGSamples.translator.initialize());
                    })
                })
        });
});

var AGSamples = window.AGSamples || {};



AGSamples.translator = {
    appWeb: "",
    hostWeb: "",
    appWebUrl: "",
    hostWebUrl: "",
    contextAppWeb: null,
    executorAppWeb: null,
    contextHostWeb: null,
    languagesList: null,
    languagesListItems: null,
    languageFrom: "nl",
    languageTo: "en",
    selectedText: "",

    initialize: function () {
        $('#btnTranslate').click(Function.createDelegate(this, this.btnTranslate_click));

        this.appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

        this.contextAppWeb = new SP.ClientContext(this.appWebUrl);

        //Cross-Site Scripting
        this.executorAppWeb = new SP.ProxyWebRequestExecutorFactory(this.appWebUrl);
        this.contextAppWeb.set_webRequestExecutorFactory(this.executorAppWeb);

//      this.contextHostWeb = new SP.AppContextSite(this.contextAppWeb, this.hostWeburl);

        this.appWeb = this.contextAppWeb.get_web();
 //       this.hostWeb = this.contextHostWeb.get_web();

 //       this.contextAppWeb.load(this.appWeb);
 //       this.contextAppWeb.load(this.hostWeb);

        this.languagesList = this.appWeb.get_lists().getByTitle('Languages');

        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml(
            "<View>" +
                "<ViewFields>" +
                    "<FieldRef Name='Title'/>" +
                    "<FieldRef Name='Code'/>" +
                "</ViewFields>" +
                "<RowLimit>50</RowLimit>" +
            "</View>"
        );
        this.languagesListItems = this.languagesList.getItems(camlQuery);

        this.contextAppWeb.load(this.languagesListItems);

        this.contextAppWeb.executeQueryAsync(
            Function.createDelegate(this, this.languagesListItemsLoaded),
            Function.createDelegate(this, this.onQueryFailed)
        );
    },

    languagesListItemsLoaded: function () {
        var listItemEnumerator = this.languagesListItems.getEnumerator();

        while (listItemEnumerator.moveNext()) {
            var listItem = listItemEnumerator.get_current();

            $('#lstFrom').append($('<option>', {
                value: listItem.get_item('Code'),
                text: listItem.get_item('Title')
            }));

            $('#lstTo').append($('<option>', {
                value: listItem.get_item('Code'),
                text: listItem.get_item('Title')
            }));
        }

        //var language = this.hostWeb.get_language();

        //$('#lstFrom').val(language);
        //$('#lstTo').val('en');

    },

    btnTranslate_click: function () {
        this.languageFrom = $("#lstFrom").val();
        this.languageTo = $("#lstTo").val();

        this.selectedText = $("#txtTextToTranslate").val();
        this.translateSelectedText();
    },

    translateSelectedText: function () {

        //http://www.bing.com/toolbox/bingsearchapi
        //https://datamarket.azure.com/account/datasets
        //https://datamarket.azure.com/dataset/bing/microsofttranslator
        //http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx


        var scriptElement = document.createElement("script");
        scriptElement.src = 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate';
        scriptElement.src += '?oncomplete=AGSamples.translator.getTranslation';
        scriptElement.src += '&appId=Bearer ' + encodeURIComponent(window.accessToken);
        scriptElement.src += '&text=' + encodeURIComponent(this.selectedText);
        scriptElement.src += '&from=' + this.languageFrom + '&to=' + this.languageTo;
        document.getElementsByTagName('head')[0].appendChild(scriptElement);
    },

    getTranslation: function (result) {
        $("#results").text(result);
    },

    onQueryFailed: function (sender, args) {
        alert('Request failed. ' + args.get_message() +
            '\n' + args.get_stackTrace());
    }
}










// Function to retrieve a query string value.
// For production purposes you may want to use
// a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

